<?php
/**
 *
 * Author: TheSmile
 * Date: 2023/5/15 15:37
 * Email: <594652523@qq.com>
 */

namespace App\Console\Commands;

use App\Models\CourseOrder;
use App\Models\CourseSection;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class OrderUpdate extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'order:update';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '更新报名状态';


    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {

        //只处理status=1或者status=2的报名订单
        $query = CourseOrder::whereRaw('(status=1 or status =2)')->orderBy('id', 'asc');
        $query->chunkById(100, function ($list) {
            foreach ($list as $item) {
                $count = $this->success($item['id']);
                if ($item['status'] == 1) {
                    if (time() > strtotime($item['start_time'])) {
                        CourseOrder::where('id', $item['id'])->update(['status' => 4]);
                        Log::info('系统已将课程订单' . $item['id'] . '从状态1变更为4');
                    } else {
                        if ($item['total'] > $count) {//如果有名额则更新排队中为报名成功即status=2
                            CourseOrder::where('id', $item['id'])->update(['status' => 2]);
                            Log::info('系统已将课程订单' . $item['id'] . '从状态1变更为2');
                        }
                    }
                }
                //查询课程订单的课程最后章节是否已大于当前时间，如果是则更新为已结课
                if ($item['status'] == 2) {
                    $num = CourseSection::where('course_id', $item['course_id'])->havingRaw('MAX(end_time) < ?', [time()])->count();
                    if ($num > 0) {
                        CourseOrder::where('id', $item['id'])->update(['status' => 3]);
                        Log::info('系统已将课程订单' . $item['id'] . '从状态2变更为3');
                    }
                }
            }
        });
    }

    //报名成功的订单统计
    public function success($courseId)
    {
        return CourseOrder::where('course_id', $courseId)->where('status', 2)->count();
    }

}
